package com.tssup.fesco.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;

import com.google.common.collect.ImmutableMap;
import com.tssup.fesco.sales.goods.persistent.mapper.RGoodsSpecificationMapper;
import com.tssup.fesco.sales.goods.persistent.mapper.RGoodsspecificationParamMapper;
import com.tssup.fesco.sales.goods.persistent.pojo.RGoodsSpecification;
import com.tssup.fesco.search.dao.ESClient;
import com.tssup.fesco.service.UpdateCatalogSpecRelationService;
import com.tssup.fesco.util.TaskLogger;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * Created by jiashen on 17-6-12.
 */
@Service
public class UpdateCatalogSpecRelationServiceImpl implements UpdateCatalogSpecRelationService {
    private final String indexName;
    private final String catalogSpecRelationTypeName;
    private final Client client;

    @Autowired
    private TaskLogger taskLogger;

    @Autowired
    RGoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    RGoodsspecificationParamMapper goodsspecificationParamMapper;

    public UpdateCatalogSpecRelationServiceImpl(Environment env, ESClient esClient) {
        super();
        indexName = env.getProperty("elasticsearch.searchArgs.indexName");
        catalogSpecRelationTypeName = env.getProperty("elasticsearch.searchArgs.catalogSpecRelationTypeName");
        client = esClient.getESClient();
    }

    @Override
    public void updateCatalogSpecRelation() throws Exception {
        taskLogger.info("Updating catalog spec relation...");
        List<RGoodsSpecification> allSpec = goodsSpecificationMapper.selectAllSpec();

        BulkRequestBuilder bulkRequest = client.prepareBulk();
        for (RGoodsSpecification spce : allSpec) {
            if (Integer.valueOf(1).equals(spce.getStatus())) {
                Integer catalogId = spce.getCatalogId();
                Integer specificationId = spce.getSpecificationId();

                List<Map> specParamList = goodsspecificationParamMapper
                    .selectBySpecificationIdForSearch(spce.getSpecificationId())
                    .stream().map(param -> ImmutableMap.of("param_name", param.getValue(), "param_id", param.getParamId())).collect(
                        Collectors.toList());

                bulkRequest.add(
                    client.prepareIndex(indexName, catalogSpecRelationTypeName, specificationId.toString())
                        .setSource(jsonBuilder()
                            .startObject()
                            .field("catalog_id", catalogId)
                            .field("specification_id", specificationId)
                            .field("specification_name", spce.getSpecificationName())
                            .field("seq", spce.getSeq())
                            .field("status", spce.getStatus())
                            .field("param_object_str", JSON.toJSONString(specParamList))
                            .endObject()

                        ));
            }
        }

        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            taskLogger.error("Update catalog spec relation get error: " + bulkResponse.buildFailureMessage());
            throw new Exception("Update catalog spec relation get error: " + bulkResponse.buildFailureMessage());
        }
    }
}
